import {
    WSController,
    OnWSMessage,
    Provide,
    OnWSConnection,
    Inject,
    WSEmit,
    OnWSDisConnection,
  } from '@midwayjs/decorator';
  
  import {WebSocketContext,SocketRequestEvent, SocketResponseEvent } from '../interface';
  
  import { ChildProcess } from 'child_process';
  import { UserService } from '../service/user';
  
  import { InjectEntityModel } from '@midwayjs/orm';
  import { Repository } from 'typeorm';
  import { Users } from '../entity/Users';
  import * as QueryString from 'querystring'
  import * as URL from 'url'
  import * as jwt from 'jsonwebtoken';
  import { Collectors } from '../entity/Collectors';
  
  @Provide()
  @WSController('/')
  export class WebSocketController {
    @Inject()
    ctx: WebSocketContext;
  
    @Inject()
    userService: UserService;
  
    @InjectEntityModel(Users)
    userModel: Repository<Users>;
  
    childs: Map<string, ChildProcess>;
  
    handle: any;
  
    constructor() {
      this.childs = new Map()
    }
  
    @OnWSConnection()
    async onConnectionMethod(ws:any,request) {
    //this.ctx.id = 1000
      

      let id:any = Date.now() * 1000 + Math.random() * 1000
      id = id.toString(36)

      this.ctx.sid = id
      console.log('on client connect',id);
  
    //   this.handle = setInterval(()=>{
    //     this.ctx.emit('Hello',"let's play a game HAHA2 (too)")
    //   },2000)
  
      let uri = URL.parse(request.url)
      let querys = QueryString.parse(uri.query)
  
      let secretKey = this.ctx.app.getConfig('token.secretKey')
      let userInfo = null
      try {
        userInfo = jwt.verify(querys.token, secretKey);
      } catch (err) {
        //ctx.error(ctx.app.ErrorCode.AUTH_INVALID);
        ws.close()
        return;
      }
  
      let collectors = await this.userModel.query(`SELECT
      u.id as user_id,
      u.name as user_name,
      p.id as company_id,
      p.name as company_name,
      c.serise_id as serise_id,
      c.name as collecor_name,
      c.push_host as push_host,
      c.push_port as push_port,
      c.uri as push_url
      FROM
      (SELECT id,name,company_id FROM users WHERE id=${userInfo.user_id}) as u
      LEFT JOIN (SELECT id,name FROM companys) as p ON p.id=u.company_id
      LEFT JOIN (SELECT company_id,serise_id,name,push_host,push_port,uri FROM collectors) as c  ON c.company_id=u.company_id`)

    // console.log(userInfo)

    // let now = Math.floor(Date.now() / 1000)
    // if (!!userInfo.expireTime && userInfo.expireTime < now) {
    //   ctx.error(ctx.app.ErrorCode.AUTH_EXPIRED);
    //   return;
    // }
  
      if(collectors == 0)
      {
        ws.close()
        return
      }
  
      let collector:Collectors = collectors[0]
  
      let port = collector.push_port
  
      this.ctx.rid = port
  
      let close = {
          OnMessage:function(message){
              ws.send(JSON.stringify(message))
          },
          disconnect(){
              ws.close()
          }
      }
      this.userService.JoinRoom(port, this.ctx.sid, close)
    }
  
    @OnWSDisConnection()
    async Disconnection(exitCode) {
      console.log('on client disconnect', this.ctx.sid);
  
      let rid = this.ctx.rid
  
      this.userService.LeaveRoom(rid, this.ctx.sid)
    }
  
    @OnWSMessage('message')
    //@WSEmit('ok')
    async gotMessage2(data,ws) {
        this.userService.SendToProcess(this.ctx.rid, data)
    }

  }
  